package com.wh.wisdomsite.xbox.st.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wh.wisdomsite.xbox.core.XboxException;
import com.wh.wisdomsite.xbox.st.dao.ContractDetailMapper;
import com.wh.wisdomsite.xbox.st.entity.Contract;
import com.wh.wisdomsite.xbox.st.entity.ContractDetail;
import com.wh.wisdomsite.xbox.st.entity.Material;
import com.wh.wisdomsite.xbox.st.service.IContractDetailService;
import com.wh.wisdomsite.xbox.st.service.IMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * 合同清单serviceImpl
 * @author 刘旭
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.st.service.impl
 * @date 2018年12月24日 14:38
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Service("contractDetailService")
@Transactional(rollbackFor = {Exception.class, RuntimeException.class})
public class ContractDetailServiceImpl extends ServiceImpl<ContractDetailMapper, ContractDetail> implements IContractDetailService {

    private static final Log logger = LogFactory.getLog(ContractDetailServiceImpl.class);

    @Autowired
    private ContractDetailMapper contractDetailMapper;

    @Autowired
    private IMaterialService iMaterialService;

    @Autowired
    private IContractDetailService iContractDetailService;



    @Override
    public Map<String, Object> getMapById(Serializable id) {
        return contractDetailMapper.getMapById(id);
    }

    @Override
    public Page<Map<String, Object>> getMapsPage(Page page, Wrapper<ContractDetail> wrapper) {
        try {
            SqlHelper.fillWrapper(page, wrapper);
            page.setRecords(this.baseMapper.getMapsPage(page, wrapper));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return page;
    }

    @Override
    public void saveContractDetail(Contract contract, HttpServletRequest request,String userId) throws Exception{
        String[] cdIds = request.getParameterValues("cdId");
        String[] materialNames = request.getParameterValues("materialName");
        String[] brand = request.getParameterValues("brand");
        String[] standardTypes = request.getParameterValues("standardType");
        String[] technicalParameter = request.getParameterValues("technicalParameter");
        String[] meteringUnits = request.getParameterValues("meteringUnit");
        String[] unitContractPrice = request.getParameterValues("unitContractPrice");
        String[] unitPrices = request.getParameterValues("unitPrice");
        String[] totalCounts = request.getParameterValues("totalCount");
        String[] remarks = request.getParameterValues("remark");
        //遍历前端传入的所有行
        for(int index = 0; index < cdIds.length; index ++ ){
            //验证数据是否正确
            if(StringUtils.isEmpty(materialNames[index])){
                throw new XboxException("物料名称不能为空");
            }
            if(StringUtils.isEmpty(standardTypes[index])){
                throw new XboxException("物料规格型号不能为空");
            }
            if(StringUtils.isEmpty(unitContractPrice[index])){
                throw new XboxException("合同单价不能为空");
            }
            if(StringUtils.isEmpty(unitPrices[index])){
                throw new XboxException("物料综合单价不能为空");
            }
            if(StringUtils.isEmpty(totalCounts[index])){
                throw new XboxException("物料总采购量不能为空");
            }
            //根据一行录入的数据，创建物料
            Material material = new Material();
            material.setMaterialName(materialNames[index]);
            material.setBrand(brand[index]);
            material.setStandardType(standardTypes[index]);
            material.setTechnicalParameter(technicalParameter[index]);
            material.setMeteringUnit(meteringUnits[index]);
            material.setUnitPrice(Double.valueOf(unitPrices[index]));

            //获取物料ID
            String maId = iMaterialService.getMaId(material);
            if(maId == null){
                throw new XboxException("获取物料ID发生异常");
            }
            //根据coId和maId查询
            EntityWrapper<ContractDetail> ew = new EntityWrapper<>();
            ew.setEntity(new ContractDetail());
            ew.eq("cd.coId", contract.getCoId());
            ew.eq("cd.maId", maId);
            ContractDetail contractDetailSearch = iContractDetailService.selectOne(ew);
            if(contractDetailSearch == null){
                //若无，则创建一条新的记录
                //每一行创建一条合同清单项
                ContractDetail contractDetail = new ContractDetail();
                contractDetail.setCdId(UUID.randomUUID().toString().replace("-",""));
                //正常获取maId
                contractDetail.setMaId(maId);
                contractDetail.setUnitContractPrice(Double.valueOf(unitContractPrice[index]));
                contractDetail.setRemark(remarks[index]);
                contractDetail.setCoId(contract.getCoId());
                contractDetail.setTotalCount(Double.valueOf(totalCounts[index]));
                //设置总价
                contractDetail.setTotalPrice(contractDetail.getTotalCount() * material.getUnitPrice());
                contractDetail.setCreateDate(new Date());
                contractDetail.setCreateBy(userId);
                iContractDetailService.insert(contractDetail);
            }else{
                //若有，则在原来的数据上，添加数量
                //新的总计数量
                Double newCount = contractDetailSearch.getTotalCount() + Double.valueOf(totalCounts[index]);
                contractDetailSearch.setTotalCount(newCount);
                contractDetailSearch.setUnitContractPrice(Double.valueOf(unitContractPrice[index]));
                contractDetailSearch.setRemark(remarks[index]);
                contractDetailSearch.setTotalPrice(newCount * material.getUnitPrice());
                contractDetailSearch.setUpdateDate(new Date());
                contractDetailSearch.setUpdateBy(userId);
                iContractDetailService.updateById(contractDetailSearch);
            }
        }
    }
}
